var mongoose = require('mongoose')
   , Post = mongoose.model('Post')
   
/*
 * GET home page.
 */
// module.exports = function(app) {
// 	app.get('/', function(req, res){
// 		res.render('index', {
// 			title: 'Express'
// 		});
// 	});
// }

//home
// exports.index = function(req, res){
//   res.render('index', { 
//   	title: '主页',
//   	user: req.session.user,
//   	success: req.flash('success').toString(),
//   	error: req.flash('error').toString()
//   });
// };

exports.index = function(req, res){
    var page = (req.query.page > 0 ? req.query.page : 1) - 1;
    var perPage = 3;
    var options = {
      perPage: perPage,
      page: page
    }
    Post.list(options, function(err, posts){
      if (err) {
          req.flash('error', err);
          return res.redirect('/');
      }
      //console.log(posts);
      Post.count().exec(function(err, count){
        res.render('index', {
            title: '主页',
            posts: posts,
            // page: page + 1,
            // pages: count > 0 ? Math.ceil(count / perPage) : 1,
            page: page + 1,
            isFirstPage: page == 0,
            isLastPage: (page * perPage + posts.length) == count,
            user: req.session.user,
            success: req.flash('success').toString(),
  	        error: req.flash('error').toString(),
        });
      });
    });
};

exports.links = function(req, res){
    res.render('links', {
        title: '友情链接',
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
    });
    
};